package uk.gov.swmprobation.cpvisibility;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;

public class SendWaiting extends IntentService {

	private static final int PHOTO_WIDTH =1024;
	private static final int PHOTO_HEIGHT =768;
	private static final int PHOTO_COMPRESSION = 100;
	private Bitmap myBitmap;
	private Bitmap scaled;
	private byte[] imageBytes;
	
	public SendWaiting() {
		super("SendWaiting");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int localId = intent.getExtras().getInt("localId");
        DatabaseHandler.getInstance(this);
		Project project = DatabaseHandler.getProject(localId);
		//File imageFile = new File(getExternalCacheDir(), "mytextfile.txt" );
		//if (imageFile.exists()) {
			SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
			String prefUserCode = sharedPref.getString("pref_user_code", "General Public");
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://env-2768543.jelastic.dogado.eu/geovation/save.xql");
			try {
			  MultipartEntity entity = new MultipartEntity();
			  	myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), project.getImageUrl());
		        scaled = Bitmap.createScaledBitmap(myBitmap, PHOTO_WIDTH, PHOTO_HEIGHT, true);
		        ByteArrayOutputStream baos = new ByteArrayOutputStream();
		        scaled.compress(Bitmap.CompressFormat.JPEG, PHOTO_COMPRESSION, baos);
		        imageBytes = baos.toByteArray();
			  String deviceId = Settings.Secure.getString(getContentResolver(),
				         Settings.Secure.ANDROID_ID);
			  entity.addPart("group", new StringBody(deviceId));
			  entity.addPart("lat", new StringBody(Double.toString(project.getLat())));
			  entity.addPart("usercode",new StringBody(prefUserCode));
			  entity.addPart("lng", new StringBody(Double.toString(project.getLng())));
			  entity.addPart("image", new ByteArrayBody(imageBytes,"image.jpg"));
			  httppost.setEntity(entity);
			  HttpResponse response = httpclient.execute(httppost);
			  String responseString = ResponceBody.getResponseBody(response);
				Document responseDoc = XMLfunctions.XMLfromString(responseString);
				NodeList nodes = responseDoc.getElementsByTagName("document");
				for (int i = 0; i < nodes.getLength(); i++) {
					Element e = (Element)nodes.item(i);
					project.setProjectId(Integer.parseInt(XMLfunctions.getValue(e, "id")));
					project.setProjectName(XMLfunctions.getValue(e, "title"));
				}
				project.setProjectType(Project.TYPE_MINE);
				project.setProjectStatus("new");
				project.setUpdated(true);
				project.save();
				Intent broadcastIntent = new Intent("uk.gov.swmprobation.cpvisibility.event.sentprojects");
				sendOrderedBroadcast(broadcastIntent, null);
			} catch (ClientProtocolException e) {
				//TODO 
			} catch (IOException e) {
				//TODO
			}
		//} else {
		//	project.setProjectStatus("photo deleted");
		//}
	}
}
